from django.db.models import ManyToManyField, DateTimeField, BooleanField
from datetime import date, datetime


def to_dict(obj, fields=None, exclude=None):
    data = {}
    for f in obj._meta.concrete_fields + obj._meta.many_to_many:
        value = f.value_from_object(obj)

        if fields and f.name not in fields:
            continue

        if exclude and f.name in exclude:
            continue

        if isinstance(f, ManyToManyField):
            value = [i.id for i in value] if obj.pk else None

        if isinstance(f, DateTimeField):
            value = value.strftime('%Y-%m-%d %H:%M:%S') if value else None

        if isinstance(f, BooleanField):
            value = int(value) if value else 0

        data[f.name] = value
    return data


def arr_to_dictarr(obj, fields):
    data_arr = []
    for f in obj:
        data = {}
        for i in range(len(fields)):
            value = f[i]
            if isinstance(value, (date, datetime,)):
                value = str(value)
            field_name = fields[i][0]
            data[field_name] = value
        data_arr.append(data)
    return data_arr
